﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace SuperiorCommon
{
    public static class ToolManager
    {

        /// <summary>
        /// 计时器开始
        /// </summary>
        /// <returns></returns>
        public static Stopwatch TimerStart()
        {
            Stopwatch watch = new Stopwatch();
            watch.Reset();
            watch.Start();
            return watch;
        }
        /// <summary>
        /// 生成短token
        /// </summary>
        /// <returns></returns>
        public static string CreateShortToken()
        {
            var rnd = new Random();
            var tokenData = new byte[8];
            rnd.NextBytes(tokenData);
            var token = Convert.ToBase64String(tokenData).Replace("=", "").Replace("+", "").Replace("/", "");
            return token;
        }
        /// <summary>
        /// 隐藏手机号中间4位
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public static string SecretPhone(string phone)
        {
            return Regex.Replace(phone, "(\\d{3})\\d{4}(\\d{4})", "$1****$2");
        }

        /// <summary>
        /// 计时器结束
        /// </summary>
        /// <param name="watch"></param>
        /// <returns></returns>
        public static string TimerEnd(Stopwatch watch)
        {
            watch.Stop();
            double costtime = watch.ElapsedMilliseconds;
            return costtime.ToString();
        }

        /// <summary>
        /// 自动生成编号  201008251145409865
        /// </summary>
        /// <returns></returns>
        public static string CreateNo()
        {
            Random random = new Random();
            string strRandom = random.Next(1000, 10000).ToString(); //生成编号 
            string code = DateTime.Now.ToString("yyyyMMddHHmmss") + strRandom;//形如
            return code;
        }

        /// <summary>
        /// 生成0-9随机数
        /// </summary>
        /// <param name="codeNum">生成长度</param>
        /// <returns></returns>
        public static string RndNum(int codeNum)
        {
            StringBuilder sb = new StringBuilder(codeNum);
            Random rand = new Random();
            for (int i = 1; i < codeNum + 1; i++)
            {
                int t = rand.Next(9);
                sb.AppendFormat("{0}", t);
            }
            return sb.ToString();

        }
        /// <summary>
        /// 删除最后结尾的一个逗号
        /// </summary>
        public static string DelLastComma(string str)
        {
            return str.Substring(0, str.LastIndexOf(","));
        }
        /// <summary>
        /// 删除最后结尾的指定字符后的字符
        /// </summary>
        public static string DelLastChar(string str, string strchar)
        {
            return str.Substring(0, str.LastIndexOf(strchar));
        }
        /// <summary>
        /// 删除最后结尾的长度
        /// </summary>
        /// <param name="str"></param>
        /// <param name="Length"></param>
        /// <returns></returns>
        public static string DelLastLength(string str, int Length)
        {
            if (string.IsNullOrEmpty(str))
                return "";
            str = str.Substring(0, str.Length - Length);
            return str;
        }

        /// <summary>
        /// 根据枚举的值获取枚举名称
        /// </summary>
        /// <typeparam name="T">枚举类型</typeparam>
        /// <param name="status">枚举的值</param>
        /// <returns></returns>
        public static string GetEnumName<T>(this int status)
        {
            return Enum.GetName(typeof(T), status);
        }

        /// <summary>
        /// datetime转换为unixtime
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static string ConvertDateTimeInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return Convert.ToInt64((time - startTime).TotalSeconds).ToString();
        }

        /// <summary>
        /// 生成随机串 随机串包含字母或数字
        /// </summary>
        /// <returns></returns>
        public static string GenerateNonceStr()
        {
            return Guid.NewGuid().ToString().Replace("-", "");
        }
        /// <summary>
        /// 检测sql注入
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsSqlin(string str)
        {
            const string Sqlint = "'、;、exec、insert、select、delete、update、count、declare、script、;、drop、truncate";
            string[] sqlArray = Sqlint.Split('、');
            for (var i = 0; i < sqlArray.Length; i++)
            {
                if (str.ToLower().IndexOf(sqlArray[i]) != -1)
                {
                    return true;
                }
            }
            return false;
        }

        public static bool IsSqlin(List<string> strs)
        {
            var res = false;
            const string Sqlint = "'、;、exec、insert、select、delete、update、count、declare、script、;、drop、truncate";
            string[] sqlArray = Sqlint.Split('、');
            foreach (var str in strs)
            {
                for (var i = 0; i < sqlArray.Length; i++)
                {
                    if (str.ToLower().IndexOf(sqlArray[i]) != -1)
                    {
                        res = true;
                        break;
                    }
                }
            }
            return res;
        }

        /// <summary>
        /// 降一篇文章内容出现的网站关键词替换成超链接
        /// </summary>
        /// <param name="article"></param>
        /// <returns></returns>
        public static string SeoReplaceWords(string article, string keywords)
        {
            string[] wordsArr = keywords.Split(new char[] { ',', '，' });
            var _tempList = new List<string>();
            for (int i = 0; i < wordsArr.Length; i++)
            {
                //创建临时关键词集合，用来存放已经加好锚文本的关键词，避免重复，比如好123,123关键词，好123已经替换了，再替换123，就出问题了
                if (article.Contains(wordsArr[i]) && !article.Contains(string.Format("<a href='{0}'>{1}</a>", "http://www.zixunmanyou.com/", wordsArr[i])))//包含这个词，并且这个词没被超链接
                {
                    if (!_tempList.Any(j => j.Contains(wordsArr[i])))
                    {
                        article = article.Replace(wordsArr[i], string.Format("<a href='{0}'>{1}</a>", "http://www.zixunmanyou.com/", wordsArr[i]));
                    }
                    _tempList.Add(wordsArr[i]);
                }
            }
            return article;
        }

        /// <summary>
        /// 判断当前会话是否是来自手机
        /// </summary>
        /// <returns></returns>
        public static bool IsMoblie()
        {
            string agent = (HttpContext.Current.Request.UserAgent + "").ToLower().Trim();

            if (agent == "" ||
                agent.IndexOf("mobile") != -1 ||
                agent.IndexOf("mobi") != -1 ||
                agent.IndexOf("nokia") != -1 ||
                agent.IndexOf("samsung") != -1 ||
                agent.IndexOf("sonyericsson") != -1 ||
                agent.IndexOf("mot") != -1 ||
                agent.IndexOf("blackberry") != -1 ||
                agent.IndexOf("lg") != -1 ||
                agent.IndexOf("htc") != -1 ||
                agent.IndexOf("j2me") != -1 ||
                agent.IndexOf("ucweb") != -1 ||
                agent.IndexOf("opera mini") != -1 ||
                agent.IndexOf("mobi") != -1 ||
                agent.IndexOf("android") != -1 ||
                agent.IndexOf("iphone") != -1)
            {
                //终端可能是手机

                return true;

            }

            return false;
        }


        /// <summary>
        /// 获取枚举名称集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static string[] GetNamesArr<T>()
        {
            return Enum.GetNames(typeof(T));
        }
        /// <summary>
        /// 将枚举转换成字典集合
        /// </summary>
        /// <typeparam name="T">枚举类型</typeparam>
        /// <returns></returns>
        public static Dictionary<string, int> getEnumDic<T>()
        {

            Dictionary<string, int> resultList = new Dictionary<string, int>();
            Type type = typeof(T);
            var strList = GetNamesArr<T>().ToList();
            foreach (string key in strList)
            {
                string val = Enum.Format(type, Enum.Parse(type, key), "d");
                resultList.Add(key, int.Parse(val));
            }
            return resultList;
        }
        /// <summary>
        /// 将枚举，转换成字典<描述和值>
        /// </summary>
        public static Dictionary<string, int> ForEnum<T>()
        {
            Dictionary<string, int> enumDic = new Dictionary<string, int>();
            Type t = typeof(T);
            Array arrays = Enum.GetValues(t);
            for (int i = 0; i < arrays.LongLength; i++)
            {
                T test = (T)arrays.GetValue(i);
                FieldInfo fieldInfo = test.GetType().GetField(test.ToString());
                object[] attribArray = fieldInfo.GetCustomAttributes(false);
                EnumDescriptionAttribute attrib = (EnumDescriptionAttribute)attribArray[0];
                enumDic.Add(attrib.Description, Convert.ToInt32(test));
            }
            return enumDic;
        }
        /// <summary>
        /// 获取指定枚举的描述
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string GetDescription(this Enum value)
        {
            FieldInfo field = value.GetType().GetField(value.ToString());
            EnumDescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(EnumDescriptionAttribute)) as EnumDescriptionAttribute;

            return attribute == null ? value.ToString() : attribute.Description;
        }

        /// <summary>
        /// 将阅读数转换成XX万
        /// </summary>
        /// <param name="readCount"></param>
        /// <returns></returns>
        public static string GetReadCountFomat(int readCount)
        {
            var result = string.Empty;
            if (readCount < 10000)
            {
                result = readCount.ToString();
            }
            else
            {
                result = string.Format("{0}万", Math.Round((double)readCount / (double)10000, 1)).ToString();
            }
            return result;
        }


        /// <summary>
        /// 时间戳转几小时前
        /// </summary>
        /// <param name="timeStamp"></param>
        /// <returns></returns>
        public static string GetFomatTime(string timeStamp)
        {
            return DateStringFromNow(GetTime(timeStamp));
        }


        /// 时间戳转为C#格式时间  
        /// </summary>  
        /// <param name=”timeStamp”></param>  
        /// <returns></returns>  
        public static DateTime GetTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime); return dtStart.Add(toNow);
        }

        /// <summary>
        /// 将时间转成几小时前。。。。。
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string DateStringFromNow(DateTime dt)
        {
            TimeSpan span = DateTime.Now - dt;
            if (span.TotalDays > 60)
            {
                return dt.ToShortDateString();
            }
            else
            {
                if (span.TotalDays > 30)
                {
                    return
                    "1个月前";
                }
                else
                {
                    if (span.TotalDays > 14)
                    {
                        return
                        "2周前";
                    }
                    else
                    {
                        if (span.TotalDays > 7)
                        {
                            return
                            "1周前";
                        }
                        else
                        {
                            if (span.TotalDays > 1)
                            {
                                return
                                string.Format("{0}天前", (int)Math.Floor(span.TotalDays));
                            }
                            else
                            {
                                if (span.TotalHours > 1)
                                {
                                    return
                                    string.Format("{0}小时前", (int)Math.Floor(span.TotalHours));
                                }
                                else
                                {
                                    if (span.TotalMinutes > 1)
                                    {
                                        return
                                        string.Format("{0}分钟前", (int)Math.Floor(span.TotalMinutes));
                                    }
                                    else
                                    {
                                        if (span.TotalSeconds >= 1)
                                        {
                                            return
                                            string.Format("{0}秒前", (int)Math.Floor(span.TotalSeconds));
                                        }
                                        else
                                        {
                                            return
                                            "1秒前";
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
